//
//  WeiBoModel.swift
//  MyWeiBo
//
//  Created by mac on 15/3/6.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

class StatusRequest: BaseObject {
    /// 采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得
    var access_token: String?
    /// 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    var since_id: Int64 = 0
    /// 若指定此参数，则返回ID小于或等于max_id的微博，默认为0
    var max_id: Int64 = 0
    /// 单页返回的记录条数，最大不超过100，默认为20。
    var count: Int = 20
    /// 返回结果的页码，默认为1
    var page: Int = 1
}

///  微博列表
class Statuses: BaseObject {
    /// 微博数据数组
    var statuses: [Status]?
    /// 微博总数
    var total_number: Int = 0
    /// 未读数量
    var has_unread: Int = 0
    
    static func classInArrayPropertyMap() -> [String: String] {
        return ["statuses": "Status"]
    }
}

///  单条微博数据
class Status: BaseObject {
    
    static let TABLENAME = "Status"
    
    var created_at: String?{
        didSet {
            let fmt = NSDateFormatter()
            fmt.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
            fmt.locale = NSLocale(localeIdentifier: "en_US")
            let createDate = fmt.dateFromString(created_at!)
            let calendar = NSCalendar.currentCalendar()
            let unit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit | NSCalendarUnit.SecondCalendarUnit
            let componetCreate =  calendar.components(unit, fromDate: createDate!)
            let componetNow = calendar.components(unit, fromDate: NSDate())
            var dateFormat: String?
            if componetCreate.year != componetNow.year {
                dateFormat = "yyyy-MM-dd"
            } else if componetCreate.month != componetNow.month {
                dateFormat = "MM-dd"
            } else if componetCreate.day != componetNow.day {
                dateFormat = "dd-HH:mm:ss"
            } else if componetCreate.hour != componetNow.hour {
                let since = componetNow.hour - componetCreate.hour
                createTimeStrig = "\(since) 小时前"
                return
            }else if componetCreate.minute != componetNow.minute {
                let since = componetNow.minute - componetCreate.minute
                createTimeStrig = "\(since) 分钟前"
                return
            } else {
                createTimeStrig = "刚刚"
                return
            }
            fmt.dateFormat = dateFormat!
            createTimeStrig = fmt.stringFromDate(createDate!)
        }
    }
    var createTimeStrig: String?
    ///  微博ID
    var id: Int = 0
    ///  微博信息内容
    var text: String?
    
    /// 带表情的富文本
    var attributString: NSAttributedString?
    
    ///  微博来源
    var source: NSString? {
        didSet {
            let startRange = source!.rangeOfString("rel=\"nofollow\">")
            let endRange = source!.rangeOfString("</a>")
            let location = startRange.location + startRange.length
            let length = endRange.location - location
            let subRange = NSMakeRange(location , length)
            if length == 0  { return }
            let subString = source!.substringWithRange(subRange)
            source = "来自 " + subString
        }
    }
    ///  被转发的原微博信息字段
    var retweeted_status: Status?
    ///  转发数
    var reposts_count: Int = 0
    ///  评论数
    var comments_count: Int = 0
    ///  表态数
    var attitudes_count: Int = 0
    ///  配图数组
    var pic_urls: [StatusPictureURL]?
    /// 用户
    var user: UserInfo?
    
    var cellHeight: CGFloat = 0
    
    /// 最终显示到界面上的图片链接
    var statusPictureURL: [StatusPictureURL]? {
        get {
            if retweeted_status != nil {
                return retweeted_status?.pic_urls
            } else {
                return pic_urls
            }
        }
    }
    
    static func classInArrayPropertyMap() -> [String: String] {
        return ["pic_urls": "StatusPictureURL"]
    }
    
    func insert() -> Bool{
        // 开启事物
        SQLite3Tool.shareInstance.benginTransaction()
        // 配图
        if pic_urls != nil {
            for item in pic_urls! {
                if !item.insertWithStatusID(id) {
                    println("插入配图失败 statusID -- \(id)")
                    SQLite3Tool.shareInstance.rollBack()
                    return false
                }
            }
        }
        // 用户信息
        if user != nil {
            if !user!.insertToTable() {
                println("插入用户信息失败 statusID -- \(user!.name)")
                SQLite3Tool.shareInstance.rollBack()
                return false
            }
        }
        
        // 转发微博
        if retweeted_status != nil {
            if !retweeted_status!.insert() {
                println("插入转发微博失败 -- \(retweeted_status!.id)")
                SQLite3Tool.shareInstance.rollBack()
                return false
            }
        }
        
        // 微博数据
        let retweeted_status_id = retweeted_status?.id ?? 0
        let statusText = text ?? ""
        let userID = user?.id ?? 0
        let sourceStr = source ?? ""
        let sql = "INSERT OR REPLACE INTO \(Status.TABLENAME) \n" +
        "( id, source, reposts_count, created_at, retweeted_status_id, attitudes_count, text, user_id, comments_count, refresh_flag) \n" +
        "VALUES \n" +
        "( \(id), '\(sourceStr)', \(reposts_count), '\(created_at!)', \(retweeted_status_id), \(attitudes_count), '\(statusText)', \(userID), \(comments_count), 1);"
        if !SQLite3Tool.shareInstance.execSQL(sql) {
            println("保存微博数据失败 -- id \(id)")
            SQLite3Tool.shareInstance.rollBack()
            return false
        }
        SQLite3Tool.shareInstance.commitTransaction()
        return true
    }
    
    class func statusWithID(statusID: Int) -> Status? {
        let sql = "SELECT \n" +
        "id, source, reposts_count, created_at, \n" +
        "retweeted_status_id, attitudes_count, \n" +
        "text, user_id, comments_count, refresh_flag \n" +
        "FROM \(Status.TABLENAME) \n" +
        "WHERE id = \(statusID)"
        println(sql)
        if let dict = SQLite3Tool.shareInstance.queryForRowDictResult(sql) {
            // 微博
            let status = Status.objectWithDictionary(dict) as! Status
            // 转发微博
            let retweeted_status_id = dict["retweeted_status_id"] as! Int
            if  retweeted_status_id > 0 {
                println("转发微博 id -- \(retweeted_status_id)")
                let retStatus = Status.statusWithID(retweeted_status_id)
                status.retweeted_status = retStatus
            }
            // 配图
            if let pics = StatusPictureURL.statusPictureURLWithStatusID(statusID) {
                status.pic_urls = pics
            }
            // 用户
            let userID = dict["user_id"] as! Int
            if userID > 0 {
                let user = UserInfo.userInfoWithID(userID)
                status.user = user
            }
            return status
        }
        
        return nil
    }
}

///  微博配图
class StatusPictureURL: BaseObject {
    
    static let TABLENAME = "StatusPictureURL"
    
    // 小图
    var thumbnail_pic: String? {
        didSet {
            largeImage_pci = thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") as String
        }
    }
    // 大图
    var largeImage_pci: String?
    
    init(dict: [String: AnyObject]) {
        self.thumbnail_pic = dict["thumbnail_pic"] as? String
    }
    
    class func statusPictureURLWithStatusID(statusID: Int) -> [StatusPictureURL]? {
        let sql = "SELECT thumbnail_pic FROM \(StatusPictureURL.TABLENAME) WHERE status_id = \(statusID);"
        println(sql)
        if let dictArray = SQLite3Tool.shareInstance.execResultSetDictionary(sql) {
            var array = [StatusPictureURL]()
            for item in dictArray {
                let itemURL = StatusPictureURL(dict: item)
                array.append(itemURL)
            }
            return array
        }
        return nil
    }
    
    ///  插入数据
    func insertWithStatusID(id: Int) -> Bool {
        let sql = "INSERT OR REPLACE INTO \(StatusPictureURL.TABLENAME) (thumbnail_pic, status_id) VALUES  ('\(thumbnail_pic!)', \(id));"
        return SQLite3Tool.shareInstance.execSQL(sql)
    }
    
}

///  用户信息
class UserInfo: BaseObject {
    
    static let TABLENAME = "UserInfo"
    
    ///  用户UID
    var id: Int = 0
    ///  用户昵称
    var screen_name: String?
    ///  友好显示名称
    var name: String?
    ///  用户头像地址（中图），50×50像素
    var profile_image_url: String?
    ///  用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    ///  性别，m：男、f：女、n：未知
    var gender: String?
    ///  粉丝数
    var followers_count: Int = 0
    ///  关注数
    var friends_count: Int = 0
    ///  微博数
    var statuses_count: Int = 0
    ///  收藏数
    var favourites_count: Int = 0
    ///  用户创建（注册）时间
    var created_at: String?
    ///  是否是微博认证用户，即加V用户，true：是，false：否
    var verified: Bool = false
    ///  认证类型，0:vip，2/3/5:企业vip，220:草根大牛
    var verified_type: Int = -1{
        didSet {
            switch verified_type {
            case 0:
                verrifyImage = UIImage(named: "avatar_vip")
            case 2,3,5:
                verrifyImage = UIImage(named: "avatar_enterprise_vip")
            case 220:
                verrifyImage = UIImage(named: "avatar_grassroot")
            default:
                verrifyImage = nil
            }
        }
    }
    ///  认证图标
    var verrifyImage: UIImage?
    
    ///  会员等级
    var mbrank: Int = 0 {
        didSet {
            if mbrank > 0 && mbrank < 7 {
                mbImage = UIImage(named: "common_icon_membership_level\(mbrank)")
            } else {
                mbImage = nil
            }
        }
    }
    ///  会员图标
    var mbImage: UIImage?
    
    func insertToTable() -> Bool {
        let sql = "INSERT OR REPLACE INTO \(UserInfo.TABLENAME) ( id ,followers_count, friends_count, avatar_large, name, created_at, verified, statuses_count, favourites_count, profile_image_url, mbrank, verified_type, gender, screen_name) VALUES ( \(id), \(followers_count),  \(friends_count), '\(avatar_large!)', '\(name!)', '\(created_at!)', \(Int(verified)), \(statuses_count), \(favourites_count), '\(profile_image_url!)', \(mbrank), \(verified_type), '\(gender!)', '\(screen_name!)');"
        return SQLite3Tool.shareInstance.execSQL(sql)
    }
    
    class func userInfoWithID(userID: Int) -> UserInfo? {
        let sql = "SELECT \n" +
        "id ,followers_count, friends_count, avatar_large, \n" +
        "name, created_at, verified, statuses_count, \n" +
        "favourites_count, profile_image_url, mbrank, \n" +
        "verified_type, gender, screen_name \n" +
        "FROM \(UserInfo.TABLENAME) \n" +
        "WHERE id = \(userID);"
        
        if let dict = SQLite3Tool.shareInstance.queryForRowDictResult(sql) {
            return (UserInfo.objectWithDictionary(dict) as! UserInfo)
        }
        return nil
    }
}
